package main.java.com.lee.io;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * created by winston on 2023/11/24
 */
public class InputStreamTest {
    public static void main(String[] args) throws IOException {
        var file = new File("/Users/leejiliang/ideaproject/gitee/demo-multi-thread/hello.txt");
        var fileInputStream = new FileInputStream(file);
//        testRead(fileInputStream);
//        testReadAllBytes(fileInputStream);
//        testCopyFile(fileInputStream);
        testCopyFileByChannel(fileInputStream);
    }

    private static void testReadAllBytes(FileInputStream fileInputStream) throws IOException {
        var allBytes = fileInputStream.readAllBytes();
        System.out.println(new String(allBytes));
    }

    /**
     * 测试读取, 这里是按照字节读取的
     *
     * @param fileInputStream 文件输入流
     * @throws IOException IOException
     */
    private static void testRead(FileInputStream fileInputStream) throws IOException {
        int read;
        while ((read = fileInputStream.read()) >= 0) {
            System.out.print((char) read);
        }
    }

    /**
     * 测试复制文件，从fileInputStream 中读取字节，用fileOutPutStream 写入
     *
     * @param fileInputStream 文件输入流
     * @throws IOException IOException
     */
    private static void testCopyFile(FileInputStream fileInputStream) throws IOException {
        var file = new File("/Users/leejiliang/ideaproject/gitee/demo-multi-thread/hello2.txt");
        var fileOutputStream = new FileOutputStream(file);
        int read;
        while ((read = fileInputStream.read()) >= 0) {
            fileOutputStream.write(read);
        }
    }

    private static void testCopyFileByChannel(FileInputStream fileInputStream) throws FileNotFoundException {
        var inChannel = fileInputStream.getChannel();
        var fileOutputStream = new FileOutputStream("/Users/leejiliang/ideaproject/gitee/demo-multi-thread/hello3.txt");
        var outChannel = fileOutputStream.getChannel();
        try {
//            var map = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
